﻿using System.Collections.Generic;
using System.Data;
using System.Data.Objects;

namespace Citi.EmailSender.Domain.Utils
{
    public class Context
    {
        private static EmailSenderEntities instance;
        private static readonly object Padlock = new object();

        /// <summary>
        /// Instancia estática do Contexto de entidades
        /// </summary>
        public static EmailSenderEntities Instance
        {
            get
            {
                lock (Padlock)
                {
                    return instance ?? (instance = new EmailSenderEntities());
                }
            }
        }

        public static void SaveChanges()
        {
            //try
            //{
                Instance.SaveChanges();
            //}
            //catch (UpdateException)
            //{
            //    throw;
            //}
            //catch
            //{
            //    ClearContext();
            //}
        }

        public static void ClearContext()
        {
            IEnumerable<ObjectStateEntry> objectStateEntries =
                Instance.ObjectStateManager.GetObjectStateEntries(EntityState.Added);
            foreach (ObjectStateEntry objectStateEntry in objectStateEntries)
                Instance.Detach(objectStateEntry.Entity);
            objectStateEntries = Instance.ObjectStateManager.GetObjectStateEntries(EntityState.Modified);
            foreach (ObjectStateEntry objectStateEntry in objectStateEntries)
                Instance.Detach(objectStateEntry.Entity);
            objectStateEntries = Instance.ObjectStateManager.GetObjectStateEntries(EntityState.Deleted);
            foreach (ObjectStateEntry objectStateEntry in objectStateEntries)
                Instance.Detach(objectStateEntry.Entity);
        }

        public static void Delete(object entity)
        {
            Instance.DeleteObject(entity);
            SaveChanges();
        }

        public static void SetOverwriteChanges<T>(ObjectSet<T> objectSet) where T : GeneralAction
        {
            try
            {
                objectSet.MergeOption = MergeOption.OverwriteChanges;
                //Instance.Refresh(RefreshMode.StoreWins, objectSet);
            }
            catch { }
        }
    }
}
